<?php
class ControllerSaleReturnLogcenterOrder extends Controller {
  private $error = array();

  public function vendor(){
    $this->load->model('sale/return_order');
    $json = array();
    $filter_name = I('get.filter_name');
    if(!$filter_name){
      $filter_name='';
    }
    $vendors = $this->model_sale_return_order->getVendors($filter_name);
    if($vendors){
      $json = $vendors;
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }

  public function product(){
    $json = array();

    if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_model'])) {
      $this->load->model('catalog/product');
      $this->load->model('catalog/option');
      $this->load->model('sale/return_order');



      if (isset($this->request->get['filter_name'])) {
        $filter['pd.name'] = array('like', '%'.$this->request->get['filter_name'].'%');
      }
      if(isset($this->request->get['filter_vendor'])){
        $filter['vendor.vendor'] = $this->request->get['filter_vendor'];
      }
      $results = $this->model_sale_return_order->getProducts($filter);

      foreach ($results as $result) {
        $option_data = array();

        $product_options = $this->model_catalog_product->getProductOptions($result['product_id']);

        foreach ($product_options as $product_option) {
          $option_info = $this->model_catalog_option->getOption($product_option['option_id']);

          if ($option_info) {
            $product_option_value_data = array();

            foreach ($product_option['product_option_value'] as $product_option_value) {
              $option_value_info = $this->model_catalog_option->getOptionValue($product_option_value['option_value_id']);

              if ($option_value_info) {
                $product_option_value_data[] = array(
                  'product_option_value_id' => $product_option_value['product_option_value_id'],
                  'option_value_id'         => $product_option_value['option_value_id'],
                  'name'                    => $option_value_info['name'],
                  'price'                   => (float)$product_option_value['price'],
                  'price_prefix'            => $product_option_value['price_prefix']
                );
              }
            }

            $option_data[] = array(
              'product_option_id'    => $product_option['product_option_id'],
              'product_option_value' => $product_option_value_data,
              'option_id'            => $product_option['option_id'],
              'name'                 => $option_info['name'],
              'type'                 => $option_info['type'],
              'value'                => $product_option['value'],
              'required'             => $product_option['required']
            );
          }
        }

        $json[] = array(
          'product_id' => $result['product_id'],
          'name'       => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
          'model'      => $result['model'],
          'cost'          => $result['product_cost'],
          'sku'         =>$result['sku'],
          'option'     => $option_data,
          'price'      => $result['price']
        );
      }
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }
  // public function exportShipping(){
  //   $po_id = I('get.po_id');
  //   if(!$po_id){
  //     $po_id = 0;
  //   }
  //   $this->load->model('sale/return_order');
  //   $po = $this->model_sale_return_order->getPo($po_id);

  //   $data['po'] = $po;

  //   if(!$po){
  //     $this->load->language('error/not_found');

  //     $this->document->setTitle($this->language->get('heading_title'));

  //     $data['heading_title'] = $this->language->get('heading_title');

  //     $data['text_not_found'] = $this->language->get('text_not_found');

  //     $data['breadcrumbs'] = array();

  //     $data['breadcrumbs'][] = array(
  //       'text' => $this->language->get('heading_title'),
  //       'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
  //     );


  //     $data['footer'] = $this->load->controller('common/footer');

  //     $this->response->setOutput($this->load->view('error/not_found.tpl', $data));
  //   }
  //   $po_products = $this->model_sale_return_order->getRoProducts($po_id);
  //   $count = 0;
  //   foreach ($po_products as $key => $po_product) {
  //     $count += $po_product['qty'];
  //   }

  //   $this->load->library('PHPExcel/PHPExcel');
  //   $objReader = PHPExcel_IOFactory::createReader('Excel5');
  //   $objPHPExcel = $objReader->load(DIR_SYSTEM . "template/order_shipping.xls");
  //   $objPHPExcel->getProperties()->setCreator("Think-tec")
  //              ->setLastModifiedBy("Think-tec")
  //              ->setTitle("Bai Huo Zhan PO")
  //              ->setSubject("Bai Huo Zhan PO")
  //              ->setDescription("Bai Huo Zhan PO")
  //              ->setKeywords("Bai Huo Zhan, Think-tec")
  //              ->setCategory("Think-tec");
  //   // $objPHPExcel->setActiveSheetIndex(0);
  //   $objActSheet = $objPHPExcel->getActiveSheet();
  //   $objPHPExcel->getActiveSheet()->getStyle('C1')->getFont()->setSize(48);
  //   $objActSheet->setCellValue('C1', $po['logcenter_info']['shipping_zone_city']);
  //   //$objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
  //   $objPHPExcel->getActiveSheet()->getStyle('B2')->getFont()->setSize(16);
  //   $objActSheet->setCellValue('B2', $po['included_order_ids']);
  //   $objPHPExcel->getActiveSheet()->getStyle('B3')->getFont()->setSize(16);
  //   $objActSheet->setCellValue('B3', $po['id']);
  //   $objPHPExcel->getActiveSheet()->getStyle('B5')->getFont()->setSize(16);
  //   $objActSheet->setCellValue('B5', $po['logcenter_info']['firstname']);
  //   $objActSheet->setCellValue('B6', $po['logcenter_info']['address_1']);
  //   $objActSheet->setCellValue('B7', $po['logcenter_info']['telephone']);

  //   //$objPHPExcel->getActiveSheet()->getStyle('A7:G'.$row_num)->getFont()->setSize(12);

  //   $objActSheet->setTitle('退货单');


  //   $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  //   ob_end_clean();
  //   // Redirect output to a client’s web browser (Excel2007)
  //   header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  //   header('Content-Disposition: attachment;filename="PO_BHZ_'.date('Y-m-d-H-i',time()).'.xlsx"');
  //   header('Cache-Control: max-age=0');
  //   // If you're serving to IE 9, then the following may be needed
  //   header('Cache-Control: max-age=1');
  //   // If you're serving to IE over SSL, then the following may be needed
  //   header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  //   header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
  //   header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
  //   header ('Pragma: public'); // HTTP/1.0
  //   $objWriter->save('php://output');
  //   exit;
  // }
  // public function export(){
  //   $po_id = I('get.po_id');
  //   if(!$po_id){
  //     $po_id = 0;
  //   }
  //   $this->load->model('sale/return_order');
  //   $po = $this->model_sale_return_order->getPo($po_id);
  //   $data['po'] = $po;
  //   if(!$po){
  //     $this->load->language('error/not_found');

  //     $this->document->setTitle($this->language->get('heading_title'));

  //     $data['heading_title'] = $this->language->get('heading_title');

  //     $data['text_not_found'] = $this->language->get('text_not_found');

  //     $data['breadcrumbs'] = array();

  //     $data['breadcrumbs'][] = array(
  //       'text' => $this->language->get('heading_title'),
  //       'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
  //     );


  //     $data['footer'] = $this->load->controller('common/footer');

  //     $this->response->setOutput($this->load->view('error/not_found.tpl', $data));
  //   }
  //   $po_products = $this->model_sale_return_order->getRoProducts($po_id);
  //   $data['po_products'] = $po_products;

  //   $this->load->library('PHPExcel/PHPExcel');
  //   $objReader = PHPExcel_IOFactory::createReader('Excel5');
  //   $objPHPExcel = $objReader->load(DIR_SYSTEM . "template/po_tpl.xls");
  //   $objPHPExcel->getProperties()->setCreator("Think-tec")
  //              ->setLastModifiedBy("Think-tec")
  //              ->setTitle("Bai Huo Zhan PO")
  //              ->setSubject("Bai Huo Zhan PO")
  //              ->setDescription("Bai Huo Zhan PO")
  //              ->setKeywords("Bai Huo Zhan, Think-tec")
  //              ->setCategory("Think-tec");
  //   // $objPHPExcel->setActiveSheetIndex(0);
  //   $objActSheet = $objPHPExcel->getActiveSheet();
  //   $objActSheet->setCellValue('B2', $po['id']);
  //   $objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
  //   $objActSheet->setCellValue('F2', date('Y-m-d H:i',time()));
  //   $objActSheet->setCellValue('B3', $po['vendor_id']);
  //   $objActSheet->setCellValue('B4', $po['vendor']['vendor_name']);
  //   $objActSheet->setCellValue('F3', $po['vendor']['firstname']);
  //   $objActSheet->setCellValue('F4', $po['vendor']['telephone']);

  //   $row_num = 6;
  //   $styleBorderOutline = array(
  //     'borders' => array(
  //       'outline' => array(
  //         'style' => PHPExcel_Style_Border::BORDER_THIN,
  //       ),
  //     ),
  //   );
  //   $objPHPExcel->getActiveSheet()->insertNewRowBefore(7, count($po_products));
  //   $count = 0;
  //   foreach ($po_products as $key => $po_product) {
  //     $row_num++;
  //     $objActSheet->setCellValue('A'.$row_num, $row_num-6);
  //     $objActSheet->setCellValue('B'.$row_num, $po_product['name'].' '.$po_product['option_name']);
  //     $objActSheet->setCellValue('C'.$row_num, $po_product['sku']);
  //     $objActSheet->setCellValue('D'.$row_num, $po_product['qty']);
  //     $objActSheet->setCellValue('E'.$row_num, $po_product['unit_price']);
  //     $objActSheet->setCellValue('F'.$row_num, $po_product['price']);
  //     $objActSheet->setCellValue('G'.$row_num, $po_product['comment']);

  //     $count += $po_product['qty'];

  //     $objPHPExcel->getActiveSheet()->getStyle('A'.$row_num)->applyFromArray($styleBorderOutline);
  //     $objPHPExcel->getActiveSheet()->getStyle('B'.$row_num)->applyFromArray($styleBorderOutline);
  //     $objPHPExcel->getActiveSheet()->getStyle('C'.$row_num)->applyFromArray($styleBorderOutline);
  //     $objPHPExcel->getActiveSheet()->getStyle('D'.$row_num)->applyFromArray($styleBorderOutline);
  //     $objPHPExcel->getActiveSheet()->getStyle('E'.$row_num)->applyFromArray($styleBorderOutline);
  //     $objPHPExcel->getActiveSheet()->getStyle('F'.$row_num)->applyFromArray($styleBorderOutline);
  //     $objPHPExcel->getActiveSheet()->getStyle('G'.$row_num)->applyFromArray($styleBorderOutline);
  //   }
  //   $row_num++;

  //   $objActSheet->setCellValue('D'.$row_num, $count);
  //   $objActSheet->setCellValue('F'.$row_num, $po['total']);
  //   $row_num++;
  //   $objActSheet->setCellValue('F'.$row_num, date('Y-m-d', strtotime($po['deliver_time'])));

  //   $objPHPExcel->getActiveSheet()->getStyle('A7:G'.$row_num)->getFont()->setSize(16);

  //   $objActSheet->setTitle('退货单');


  //   $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  //   ob_end_clean();
  //   // Redirect output to a client’s web browser (Excel2007)
  //   header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  //   header('Content-Disposition: attachment;filename="PO_BHZ_'.date('Y-m-d-H-i',time()).'.xlsx"');
  //   header('Cache-Control: max-age=0');
  //   // If you're serving to IE 9, then the following may be needed
  //   header('Cache-Control: max-age=1');
  //   // If you're serving to IE over SSL, then the following may be needed
  //   header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  //   header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
  //   header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
  //   header ('Pragma: public'); // HTTP/1.0
  //   $objWriter->save('php://output');
  //   exit;
  // }

  public function index() {

    $this->document->setTitle('退货单');

    $this->load->model('sale/return_order');

    $this->getList();
  }

  public function add() {
    $this->document->setTitle('新增退货单');
    $this->document->addScript('view/javascript/angular.js');
    $this->document->addScript('view/javascript/bhz_ctl.js');

    $this->load->model('sale/return_order');

    $this->form();
  }

  public function view(){

    $this->document->setTitle('查看退货单');

    $this->document->addScript('view/javascript/angular.js');
    $this->document->addScript('view/javascript/bhz_ctl.js');

    $this->load->model('sale/return_order');
    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '退货单',
      'href' => $this->url->link('sale/return_logcenter_order', 'token=' . $this->session->data['token'] , 'SSL')
    );

    $data['token'] = $this->session->data['token'];

    $id = I('get.ro_id');
    if(!$id){
      $id=0;
    }


    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }

    $ro = $this->model_sale_return_order->getRo($id);

    $data['ro'] = $ro;
    $ro_products = $this->model_sale_return_order->getRoProducts($id);
    $data['ro_products'] = $ro_products;
    $ro_histories = $this->model_sale_return_order->getRoHistory($id);
    $data['ro_histories'] = $ro_histories;
    $data['included_orders'] = explode(',', $po['included_order_ids']);

    if($ro['status']==3) {
      $data['forceCompleteBtn'] = '审核完成退货单';
    }

    if($ro['status']==7) {
      $data['need_allow'] = true;
    }

    if($ro['status']==0) {
      $data['need_confirm'] = true;
    }

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/return_logcenter_order_view.tpl', $data));
  }

  public function save(){
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/return_order');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
      if(!$data['deliver_time'] || !$data['products']){
        $this->response->setOutput(json_encode(array('success'=>false, 'info'=>'数据不完整')));
      }
      else{
        $ro_id = $this->model_sale_return_order->addRo($data, $this->user->getId());
      }
      $this->response->setOutput(json_encode(array('success'=>true, 'info'=>$ro_id)));
      return;
    }
  }

  public function confirmStock(){
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/return_order');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);

      // $id = I('post.po_id');
      $id = $data['ro_id'];
      if(!$id){
        $id=0;
      }
      $ro = $this->model_sale_return_order->getRo($id);
      //判断po状态，如果是已经结算或者已经关闭，
      if($ro['status'] == 1 || $ro['status'] == 2) {
        $this->response->setOutput(json_encode(array('error'=>'不能修改退货单')));
        return;
      }


        $this->model_sale_return_order->changeRoStatus($id, 1);
        //确认退货单

        $this->load->model('catalog/logcenter');
        $comment = '物流中心确认退货单';

        $this->model_sale_return_order->addRoHistory($id, $this->user->getId(), $this->user->getUserName(), $comment);


      $this->response->setOutput(json_encode(array('success'=>'物流中心成功确认退货单')));
      return;
    }
  }

  public function delete() {
    $json = array();

    $this->load->model('sale/return_order');

    $id = I('get.ro_id');
    if(!$id){
      $id=0;
    }

    $ro = $this->model_sale_return_order->getRo($id);
    if(!$ro||$ro['status']!=0) {
      $json['error'] = '非新增状态退货单不能删除';
    }
    else {
      $this->model_sale_return_order->deleteRo($id);
      $json['success'] = '删除成功';
    }

    if (isset($this->request->server['HTTP_ORIGIN'])) {
      $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
      $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
      $this->response->addHeader('Access-Control-Max-Age: 1000');
      $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }

  protected function form(){
        $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '退货单',
      'href' => $this->url->link('sale/return_logcenter_order', 'token=' . $this->session->data['token'] , 'SSL')
    );

    $data['token'] = $this->session->data['token'];

    $id = I('get.ro_id');
    if(!$id){
      $id=0;
    }


    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }

    $ro = $this->model_sale_return_order->getRo($id);
    $data['ro'] = $ro;
    $po_products = $this->model_sale_return_order->getRoProducts($id);
    $data['ro_products'] = $ro_products;

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/return_logcenter_order.tpl', $data));
  }



  protected function getList() {
    $page = I('get.page');
    if(!$page){
      $page = 1;
    }
    if($this->user->getLp()){
      $filter['ro.user_id'] = $this->user->getId();
    }
    else if($this->user->getVp()){
      $filter['ro.vendor_id'] = $this->user->getId();
    }
    else{

    }
    $data = I('get.');

    if(isset($data['filter_date_start'])){
      $filter_date_start = $data['filter_date_start'];
    }else{
      $filter_date_start = '0000-00-00';
    }

    if(isset($data['filter_date_end'])){
      $filter_date_end = $data['filter_date_end'];
    }else{
      $filter_date_end = '9999-12-31';
    }

    $filter['ro.date_added'] = array('between',array($filter_date_start,$filter_date_end));
    if(isset($data['filter_vendor_name'])){
      $filter_vendor_name = trim($data['filter_vendor_name']);
      $filter['v.vendor_name'] = array('like',"%".$filter_vendor_name."%");
    }

    if(isset($data['filter_logcenter'])){
      $filter_logcenter = trim($data['filter_logcenter']);
      $filter['lg.logcenter_name'] = array('like',"%".$filter_logcenter."%");
    }

    if(isset($data['filter_status'])){
      $filter_status = trim($data['filter_status']);
      if($filter_status!='*'){
        $filter['ro.status'] = $filter_status;
      }
    }else{
      $data['filter_status'] = '*';
    }

    $ro_list =  $this->model_sale_return_order->getList($page, $filter);
    $order_total = $this->model_sale_return_order->getListCount($filter);
    $data['status_array'] = getRoStatus();
    $data['status_array']['*'] = '全部';
    $pagination = new Pagination();
    $pagination->total = $order_total;
    $pagination->page = $page;
    $pagination->limit = $this->config->get('config_limit_admin');
    $pagination->url = $this->url->link('sale/return_logcenter_order', 'token=' . $this->session->data['token'] . '&page={page}'.'&filter_date_end='.$filter_date_end.'&filter_date_start='.$filter_date_start.'&filter_logcenter='.$filter_logcenter, 'SSL');

    $data['pagination'] = $pagination->render();

    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '退货单',
      'href' => $this->url->link('sale/return_logcenter_order', 'token=' . $this->session->data['token'] , 'SSL')
    );

    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }

    $data['token'] = $this->session->data['token'];

    $data['ro_list'] = $ro_list;

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/return_logcenter_order_list.tpl', $data));
  }

  function validateDate($date, $format = 'Y-m-d H:i:s')
  {
      $d = DateTime::createFromFormat($format, $date);
      return $d && $d->format($format) == $date;
  }

  public function genVendorBill(){
    $vendor_bill_month = I('get.year_month');
    $month_valid = $this->validateDate($vendor_bill_month, 'Y-m');
    if(!$month_valid) {
      $this->session->data['error'] = '请选择有效的年月日期';
      $this->response->redirect($this->url->link('sale/order', 'token=' . $this->session->data['token'], 'SSL'));
    }
    //获取选择月份之前半年内所有还未对账的完成状态的订单
    $d = DateTime::createFromFormat('Y-m', $vendor_bill_month);
    $cur_year_month = $d->format('Y-m-01');
    $cur_month = $d->format('Y-m-21');
    $d->modify('-6 month');
    $end_month = $d->format('Y-m-d');
    $this->load->model('sale/vendor_bill');
    $this->load->model('sale/return_order');
    $billed_po = $this->model_sale_vendor_bill->getBilledPo($cur_month, $end_month);
    $billed_po_ids = array();
    foreach ($billed_po as $bo) {
      $billed_po_ids[] = $bo['po_id'];
    }

    $vendor_ids = $this->model_sale_return_order->getVendorIdsFromPo($cur_month, $end_month, $billed_po_ids);

    foreach ($vendor_ids as $vendor_id) {
      $bill_data = $this->model_sale_return_order->getToBillPo($cur_month, $end_month, $billed_po_ids, $vendor_id['vendor_id']);
      $bill_data_full[$vendor_id['vendor_id']] = $bill_data;
    }

    $commission = 1;
    foreach ($bill_data_full as $vendor_id=>$bill_data) {
      $po_total = 0;
      $po_ids = array();
      foreach ($bill_data as $po) {
        $po_total += (float)$po['total'];
        $po_ids[] = $po['id'];
      }
      $commission_total = $po_total*$commission;
      $data = array();

      //此处的$vendor_id是po表中的vendor_id 对应的是 vendors表中的user_id
      $this->load->model('catalog/vendor');
      $vendor_info = $this->model_catalog_vendor->getVendorByUserId($vendor_id);
      $data['vendor_id'] = $vendor_info['vendor_id'];
      $data['year_month'] = $cur_year_month;
      $data['total'] = $commission_total;
      $data['po_total'] = $po_total;
      $data['date_added'] = date('Y-m-d H:i:s', time());
      $vendor_bill_id = $this->model_sale_vendor_bill->saveVendorBill($data, $po_ids);

      //添加生成po操作记录
      $this->load->model('user/user');
      $user_info = $this->model_user_user->getUser($this->user->getId());
      $comment = '新增品牌商对账单';
      $this->model_sale_vendor_bill->addVendorBillHistory($vendor_bill_id, $this->user->getId(), $user_info['fullname'], $comment);
    }



    $this->session->data['success'] = '生成品牌厂商对账单成功';
    $this->response->redirect($this->url->link('sale/vendor_bill', 'token=' . $this->session->data['token'], 'SSL'));
  }

  public function forceCompletePo() {
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/return_order');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
      // $id = I('post.po_id');
      $id = $data['po_id'];
      if(!$id){
        $id=0;
      }
      $po = $this->model_sale_return_order->getPo($id);
      //判断po状态
      if($po['status'] != 3) {
        $this->response->setOutput(json_encode(array('error'=>'只能审核完成部分收货状态退货单')));
        return;
      }

      if($po['status'] == 3) {
        //修改po单的total
        $po_products = $this->model_sale_return_order->getRoProducts($id);
        $new_total = 0;
        foreach ($po_products as $po_product) {
          $new_total += (float)$po_product['unit_price']*(float)$po_product['delivered_qty'];
        }
        $this->model_sale_return_order->setPoTotal($id, $new_total);

        //修改po的status到审核完成
        $po_status = 6;
        $this->model_sale_return_order->changePoStatus($id, $po_status);

        //添加po状态修改操作记录
        $this->load->model('user/user');
        $user_info = $this->model_user_user->getUser($this->user->getId());
        $comment = '审核完成退货单。退货单金额改为：' . $new_total . '￥';
        $this->model_sale_return_order->addPoHistory($id, $this->user->getId(), $user_info['fullname'], $comment);
      }

      $this->response->setOutput(json_encode(array('success'=>'修改退货单状态成功')));
      return;
    }
  }
  public function exportLists(){

    $this->load->model('sale/return_order');

    $data = I('get.');

    if(isset($data['filter_date_start'])){
      $filter_date_start = $data['filter_date_start'];
    }else{
      $filter_date_start = '0000-00-00';
    }

    if(isset($data['filter_date_end'])){
      $filter_date_end = $data['filter_date_end'];
    }else{
      $filter_date_end = '9999-12-31';
    }

    $filter['ro.date_added'] = array('between',array($filter_date_start,$filter_date_end));
    // if(isset($data['filter_vendor_name'])){
    //   $filter_vendor_name = trim($data['filter_vendor_name']);
    //   $filter['v.vendor_name'] = array('like',"%".$filter_vendor_name."%");
    // }

    // if(isset($data['filter_logcenter'])){
    //   $filter_logcenter = trim($data['filter_logcenter']);
    //   $filter['lg.logcenter_name'] = array('like',"%".$filter_logcenter."%");
    // }

    $Lp = $this->user->getLp();
    $filter['lg.logcenter_id'] = $Lp;


    if(isset($data['filter_status'])){
      $filter_status = trim($data['filter_status']);
      if($filter_status!='*'){
        $filter['ro.status'] = $filter_status;
      }
    }else{
      $data['filter_status'] = '*';
    }

    $ro_list =  $this->model_sale_return_order->getAllProductList($filter);


    $status_array = getRoStatus();
    foreach ($ro_list as $key => $value) {
      $save_data[] = array(
        'id'            =>  $key+1,
        'name'          =>  $value['name'],
        'option_name'   =>  $value['option_name'],
        'qty'           =>  $value['qty'],
        'price'         =>  $value['price'],
        'unit_price'    =>  $value['unit_price'],
        'deliver_time'  =>  $value['deliver_time'],
        'packing_no'    =>  $value['packing_no'],
        'date_added'    =>  $value['date_added'],
        'total'         =>  $value['qty']*$value['price'],
        'vendor_name'   =>  $value['vendor_name'],
        'model'         =>  $value['model'],
        'logcenter_name'=>  $value['logcenter_name'],
        'status'        =>  $status_array[$value['status']],
        );
    }

    $this->load->library('PHPExcel/PHPExcel');
    $objPHPExcel = new PHPExcel();
    $objProps = $objPHPExcel->getProperties();
    $objProps->setCreator("Think-tec");
    $objProps->setLastModifiedBy("Think-tec");
    $objProps->setTitle("Think-tec Contact");
    $objProps->setSubject("Think-tec Contact Data");
    $objProps->setDescription("Think-tec Contact Data");
    $objProps->setKeywords("Think-tec Contact");
    $objProps->setCategory("Think-tec");
    $objPHPExcel->setActiveSheetIndex(0);
    $objActSheet = $objPHPExcel->getActiveSheet();

    $objActSheet->setTitle('Sheet1');
    $col_idx = 'A';
    $headers = array( '编号','商品名称','选项', '单价','数量','总价','箱入数', '创建时间', '退货时间', '供应商', '物流中心',     '型号', '退货单状态');
    $row_keys = array('id','name','option_name','price','qty','total','packing_no','date_added', 'deliver_time', 'vendor_name','logcenter_name',  'model', 'status');
    foreach ($headers as $header) {
      $objActSheet->setCellValue($col_idx++.'1', $header);
    }
    //添加物流信息
    $i = 2;
    foreach ($save_data as $rlst) {
      $col_idx = 'A';
      foreach ($row_keys as $rk) {
        // $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]);
        $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
      }
      $i++;
    }

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

    ob_end_clean();
    // Redirect output to a client’s web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="return_logcenter_order_'.date('Y-m-d',time()).'.xlsx"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');

    // If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
    $objWriter->save('php://output');
    exit;
  }

  public function exportTpl(){

    $this->load->library('PHPExcel/PHPExcel');
    $objPHPExcel = new PHPExcel();
    $objProps = $objPHPExcel->getProperties();
    $objProps->setCreator("Think-tec");
    $objProps->setLastModifiedBy("Think-tec");
    $objProps->setTitle("Think-tec Contact");
    $objProps->setSubject("Think-tec Contact Data");
    $objProps->setDescription("Think-tec Contact Data");
    $objProps->setKeywords("Think-tec Contact");
    $objProps->setCategory("Think-tec");
    $objPHPExcel->setActiveSheetIndex(0);
    $objActSheet = $objPHPExcel->getActiveSheet();

    $objActSheet->setTitle('Sheet1');
    $col_idx = 'A';
    $headers = array( '条码','选项名','数量');
    foreach ($headers as $header) {
      $objActSheet->setCellValue($col_idx++.'1', $header);
    }

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

    ob_end_clean();
    // Redirect output to a client’s web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="return_logcenter_order_exp_tpl'.date('Y-m-d',time()).'.xlsx"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');

    // If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
    $objWriter->save('php://output');
    exit;
  }

  public function import() {
    $json = array();
    if (1) {
      if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
        // Sanitize the filename
        $filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
        // Validate the filename length
        if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 128)) {
          $json['error'] = '文件名过短';
        }
        // Allowed file extension types
        $allowed = array('xls','xlsx');
        if (!in_array(strtolower(substr(strrchr($filename, '.'), 1)), $allowed)) {
          $json['error'] = '请上传xls或者xlsx文件';
        }
        // Return any upload error
        if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
          $json['error'] = '上传出现错误';
        }
      }
    }
    else {
      $json['error'] = '上传失败';
    }

    if (!$json) {
      $this->load->library('PHPExcel/PHPExcel');
      $savePath = $this->request->files['file']['tmp_name'];
      $PHPExcel = new PHPExcel();
      $PHPReader = new PHPExcel_Reader_Excel2007();
      if(!$PHPReader->canRead($savePath)){
        $PHPReader = new PHPExcel_Reader_Excel5();
      }
      $PHPExcel = $PHPReader->load($savePath);
      $currentSheet = $PHPExcel->getSheet(0);
      $allRow = $currentSheet->getHighestRow();
      //获取order_product_id, express_name, express_number在excel中的index
      $sku_idx = $option_name_idx = $qty_idx = 0;
      $tmp_idx = 'A'; //假设导入表格不会长于Z
      $currentRow = 1;
      while(($tmp_idx === 0 || $option_name_idx === 0 || $qty_idx === 0)&&$tmp_idx<'Z') {
        switch (trim((String)$currentSheet->getCell($tmp_idx.$currentRow)->getValue())) {
          case '条码':
            $sku_idx = $tmp_idx;
            break;
          case '选项名':
            $option_name_idx = $tmp_idx;
            break;
          case '数量':
            $qty_idx = $tmp_idx;
            break;
        }
        $tmp_idx++;
      }

      if(0 === $sku_idx || 0 === $option_name_idx||0 === $qty_idx) {
        $json['error'] = '请检查文件第一行是否有：条码、选项名、数量';
      }

      if (!$json) {
        $this->load->model('catalog/product');
        $products_info = array();
        for ($currentRow = 2;$currentRow <= $allRow;$currentRow++) {
          $sku = (String)$currentSheet->getCell($sku_idx.$currentRow)->getValue();
          $option_name = (String)$currentSheet->getCell($option_name_idx.$currentRow)->getValue();
          $qty = (String)$currentSheet->getCell($qty_idx.$currentRow)->getValue();
          //检查sku是否存在
          $product = $this->model_catalog_product->getProductBySku($sku);
          // var_dump($product);
          if(empty($product)) {
            $json['error'] = '第' . $currentRow . '行条码对应商品未找到';
          }
          //检查此商品是否有选项
          if(!isset($json['error'])) {
            if(!empty($product['option'])) {
              //如果有选项则判断当前的选项是否和sku匹配
              if(!array_key_exists($option_name, $product['option'])) {
                $json['error'] = '第' . $currentRow . '行选项名不属于此条码商品';
              }
            }
          }
          // var_dump($product);die();
          if(isset($json['error'])) {
            $this->response->addHeader('Content-Type: application/json');
            $this->response->setOutput(json_encode($json));
            return;
          }

          $product_cost = M('vendor')->where(array('vproduct_id'=>$product['product_id']))->getField('product_cost');
          $product_data['product_id'] = $product['product_id'];
          $product_data['qty'] = $qty;
          $product_data['delivered_qty'] = 0;
          $product_data['unit_price'] = $product_cost;
          $product_data['status'] = $product['status'];
          $product_data['name'] = $product['name'];
          $product_data['sku'] = $product['sku'];
          $product_data['comment'] = '';
          $product_data['option'] = array();
          $product_data['option']['product_option_value_id'] = $product['option'][$option_name];
          $product_data['option']['name'] = array_key_exists($option_name, $product['option'])?$option_name:'';

          $products_info[] = $product_data;
        }

        //拼装addRo数据
        $ro_data['deliver_time'] = date('Y-m-d H:i:s', time());
        $ro_data['included_order_ids'] = '';
        $ro_data['products'] = $products_info;
        //调用addRo
        $this->load->model('sale/return_order');
        $ro_id = $this->model_sale_return_order->addRo($ro_data, $this->user->getId());

        $this->model_sale_return_order->addRoHistory($ro_id, $this->user->getId(), $this->user->getUserName(), '导入退货单');
      }

      if (!isset($json['error'])) {
        $json['success'] = sprintf('更新新建退货单 %s条商品记录', count($ro_data['products']));
      }
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));

  }
    public function importReward() {
    $json = array();
    if (1) {
      if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
        // Sanitize the filename
        $filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
        // Validate the filename length
        if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 128)) {
          $json['error'] = '文件名过短';
        }
        // Allowed file extension types
        $allowed = array('xls','xlsx');
        if (!in_array(strtolower(substr(strrchr($filename, '.'), 1)), $allowed)) {
          $json['error'] = '请上传xls或者xlsx文件';
        }
        // Return any upload error
        if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
          $json['error'] = '上传出现错误';
        }
      }
    }
    else {
      $json['error'] = '上传失败';
    }

    if (!$json) {
      $this->load->library('PHPExcel/PHPExcel');
      $savePath = $this->request->files['file']['tmp_name'];
      $PHPExcel = new PHPExcel();
      $PHPReader = new PHPExcel_Reader_Excel2007();
      if(!$PHPReader->canRead($savePath)){
        $PHPReader = new PHPExcel_Reader_Excel5();
      }
      $PHPExcel = $PHPReader->load($savePath);
      $currentSheet = $PHPExcel->getSheet(0);
      $allRow = $currentSheet->getHighestRow();
      //获取order_product_id, express_name, express_number在excel中的index
      $reward_num_idx = $reward_name_idx = $order_idx = $name_idx = $telephone_idx = $zone_idx = $city_idx = $area_idx = $address_idx = $code_idx = $reward_level_name_idx = $discount_idx = 0;
      $tmp_idx = 'A'; //假设导入表格不会长于Z
      $currentRow = 1;
      while(($reward_num_idx === 0 || $reward_name_idx === 0 || $order_idx === 0 || $name_idx === 0 || $telephone_idx === 0 || $zone_idx === 0 || $city_idx === 0 || $area_idx === 0 || $address_idx === 0 || $code_idx === 0 || $reward_level_name_idx === 0 || $discount_idx === 0)&&$tmp_idx<'Z') {
        switch (trim((String)$currentSheet->getCell($tmp_idx.$currentRow)->getValue())) {
          case '中奖编号':
            $reward_num_idx = $tmp_idx;
            break;
          case '活动名称':
            $reward_name_idx = $tmp_idx;
            break;
          case '订单号':
            $order_idx = $tmp_idx;
            break;
          case '收货人':
            $name_idx = $tmp_idx;
            break;
          case '电话':
            $telephone_idx = $tmp_idx;
            break;
          case '省市':
            $zone_idx = $tmp_idx;
            break;
          case '市县':
            $city_idx = $tmp_idx;
            break;
          case '县区':
            $area_idx = $tmp_idx;
            break;
          case '地址':
            $address_idx = $tmp_idx;
            break;
          case '邮编':
            $code_idx = $tmp_idx;
            break;
          case '奖项':
            $reward_level_name_idx = $tmp_idx;
            break;
          case '产品名':
            $discount_idx = $tmp_idx;
            break;
        }
        $tmp_idx++;
      }

      if($reward_num_idx === 0 || $reward_name_idx === 0 || $order_idx === 0 || $name_idx === 0 || $telephone_idx === 0 || $zone_idx === 0 || $city_idx === 0 || $area_idx === 0 || $address_idx === 0 || $code_idx === 0 || $reward_level_name_idx === 0 || $discount_idx === 0) {
        $json['error'] = '请检查文件第一行是否齐全';
      }

      if (!$json) {
        for ($currentRow = 2;$currentRow <= $allRow;$currentRow++) {
          $reward_num = (String)$currentSheet->getCell($reward_num_idx.$currentRow)->getValue();
          $reward_name = (String)$currentSheet->getCell($reward_name_idx.$currentRow)->getValue();
          $order = (String)$currentSheet->getCell($order_idx.$currentRow)->getValue();
          $name = (String)$currentSheet->getCell($name_idx.$currentRow)->getValue();
          $telephone = (String)$currentSheet->getCell($telephone_idx.$currentRow)->getValue();
          $zone = (String)$currentSheet->getCell($zone_idx.$currentRow)->getValue();
          $city = (String)$currentSheet->getCell($city_idx.$currentRow)->getValue();
          $area = (String)$currentSheet->getCell($area_idx.$currentRow)->getValue();
          $address = (String)$currentSheet->getCell($address_idx.$currentRow)->getValue();
          $code = (String)$currentSheet->getCell($code_idx.$currentRow)->getValue();
          $reward_level_name = (String)$currentSheet->getCell($reward_level_name_idx.$currentRow)->getValue();
          $discount = (String)$currentSheet->getCell($discount_idx.$currentRow)->getValue();

          $customer_id = M('customer')->where('telephone='.$telephone)->getField('customer_id');

          if(empty($customer_id)) {
            $json['error'] = '第' . $currentRow . '会员未找到'.$telephone;
          }

          // var_dump($product);die();
          if(isset($json['error'])) {
            $this->response->addHeader('Content-Type: application/json');
            $this->response->setOutput(json_encode($json));
            return;
          }


          $reward_data['customer_id'] = $customer_id;
          $reward_data['discount'] = $discount;
          $reward_data['reward_name'] = $reward_name;
          $reward_data['total'] = 588;
          $reward_data['reward_num'] = $reward_num;


          $rewards_info[] = $reward_data;
        }


        //调用addRo
        $this->load->model('sale/return_order');
        $this->model_sale_return_order->addCoupons($rewards_info);
      }

      if (!isset($json['error'])) {
        $json['success'] = sprintf('更新新建退货单 %s条商品记录', count($ro_data['products']));
      }
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));

  }


  public function importCustomer() {
		$json = array();

			if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
				// Sanitize the filename
				$filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
				// Validate the filename length
				if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 128)) {
					$json['error'] = '文件名过短';
				}
				// Allowed file extension types
				$allowed = array('xls','xlsx');
				if (!in_array(strtolower(substr(strrchr($filename, '.'), 1)), $allowed)) {
					$json['error'] = '请上传xls或者xlsx文件';
				}
				// Return any upload error
				if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
					$json['error'] = '上传出现错误';
				}
			}

		else {
			$json['error'] = '上传失败';
		}

		if (!$json) {
			$this->load->library('PHPExcel/PHPExcel');
			$savePath = $this->request->files['file']['tmp_name'];
			$PHPExcel = new PHPExcel();
			$PHPReader = new PHPExcel_Reader_Excel2007();
			if(!$PHPReader->canRead($savePath)){
				$PHPReader = new PHPExcel_Reader_Excel5();
			}
			$PHPExcel = $PHPReader->load($savePath);
			$currentSheet = $PHPExcel->getSheet(0);
			$allRow = $currentSheet->getHighestRow();
			//获取order_product_id, express_name, express_number在excel中的index
			$telephone = $type =0;
            //$tel = $number = $password = 0;
			$tmp_idx = 'A'; //假设导入表格不会长于Z
			$currentRow = 1;
			while(($telephone === 0 || $type === 0)&&$tmp_idx<'Z') {
				switch (trim((String)$currentSheet->getCell($tmp_idx.$currentRow)->getValue())) {
					case '电话':
						$telephone = $tmp_idx;
						break;
					case '类型':
						$type = $tmp_idx;
						break;
				}
				$tmp_idx++;
			}

			if(0 === $telephone || 0 === $type ) {
				$json['error'] = '请检查文件第一行是否有：电话、类型';
			}

			if (!$json) {
				$express_infos = array();
				for ($currentRow = 2;$currentRow <= $allRow;$currentRow++) {
					$express_infos[] = array(
						'telephone' => (string)$currentSheet->getCell($telephone.$currentRow)->getValue(),
						'type' => (string)$currentSheet->getCell($type.$currentRow)->getValue(),
						);

                // 判断excel表里是否有空
                //  if('' == $currentSheet->getCell($tel.$currentRow)->getValue() || '' == $currentSheet->getCell($number.$currentRow)->getValue() ||  '' == $currentSheet->getCell($password.$currentRow)->getValue()){
                //            $json['error'] = '请检查文件第'.$currentRow.'行是否有空';
                //            $this->response->setOutput(json_encode($json));
                //            return;
                //     }

				}
        //session('arr',$express_infos);die();
				// 判断数组里面是否有空，有的话就提取出行号
          $customer_replace=array(
              'KA'=>4,
              'KB'=>5,
              'KC'=>6,
              'KD'=>7
          );
                $arr=array();
                foreach($express_infos as $k => $v){
                    if('' == $express_infos[$k]['telephone'] || '' == $express_infos[$k]['type']){
                        $arr[]=$k+2;
                    }
                    if(array_key_exists($express_infos[$k]['type'],$customer_replace)){
                        $express_infos[$k]['type'] = $customer_replace[$express_infos[$k]['type']];
                    }
                }
                // session('arr',$express_infos);
                //返回错误信息
                  if(!empty($arr)){
                      $json['error'] = '请检查文件第'.implode(',',$arr).'行是否有空';
                  }else{
                      $this->load->model('customer/customer');
                      $this->model_customer_customer->editShopType($express_infos);
                      $json['success'] = '成功更改'.count($express_infos).'条终端';
                  }

			}
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

}
